using System.Linq.Expressions;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework.Models.Common;

namespace WinformDevFramework
{
    public partial class Frmw_Supplier : BaseForm1
    {
        private Iw_SupplierServices _w_SupplierServices;

        public Frmw_Supplier(Iw_SupplierServices w_SupplierServices)
        {
            _w_SupplierServices = w_SupplierServices;
            InitializeComponent();
        }

        public override void Init()
        {
            base.Init();

            // 初始化数据，默认显示第一页
            var data = GetData(string.Empty, 1, _pageSize);
            this.dataGridViewList.DataSource = data.Items;

            // 设置列标题
            this.dataGridViewList.Columns["SupplierName"].HeaderText = "名称";
            this.dataGridViewList.Columns["ContactPerson"].HeaderText = "联系人";
            this.dataGridViewList.Columns["PhoneNumber"].HeaderText = "手机号码";
            this.dataGridViewList.Columns["Email"].HeaderText = "邮箱";
            this.dataGridViewList.Columns["BeginPay"].HeaderText = "期初应付";
            this.dataGridViewList.Columns["EndPay"].HeaderText = "期末应付";
            this.dataGridViewList.Columns["TaxtRate"].HeaderText = "税率";
            this.dataGridViewList.Columns["SortOrder"].HeaderText = "排序";
            this.dataGridViewList.Columns["Status"].HeaderText = "状态";
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["Faxing"].HeaderText = "传真";
            this.dataGridViewList.Columns["Address"].HeaderText = "地址";
            this.dataGridViewList.Columns["Bank"].HeaderText = "开户行";
            this.dataGridViewList.Columns["TaxpayerNumber"].HeaderText = "纳税人识别号";
            this.dataGridViewList.Columns["BankAccount"].HeaderText = "银行账号";
            this.dataGridViewList.Columns["LandlinePhone"].HeaderText = "固定电话";
            this.dataGridViewList.Columns["SupplierCode"].HeaderText = "供应商编码";

            // 初始化分页控件状态
            UpdatePaginationControls(data.TotalCount);

            // 设置工具栏按钮状态
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_Supplier;

            // 主键赋值
            this.txtID.Text = model.ID.ToString();

            this.SupplierName.Text = model.SupplierName?.ToString();
            this.ContactPerson.Text = model.ContactPerson?.ToString();
            this.PhoneNumber.Text = model.PhoneNumber?.ToString();
            this.Email.Text = model.Email?.ToString();
            this.BeginPay.Text = model.BeginPay?.ToString();
            this.EndPay.Text = model.EndPay?.ToString();
            this.TaxtRate.Text = model.TaxtRate?.ToString();
            this.SortOrder.Text = model.SortOrder?.ToString();
            this.Status.Checked = model.Status.Value;
            this.Remark.Text = model.Remark?.ToString();
            this.Faxing.Text = model.Faxing?.ToString();
            this.Address.Text = model.Address?.ToString();
            this.Bank.Text = model.Bank?.ToString();
            this.TaxpayerNumber.Text = model.TaxpayerNumber?.ToString();
            this.BankAccount.Text = model.BankAccount?.ToString();
            this.LandlinePhone.Text = model.LandlinePhone?.ToString();
            this.SupplierCode.Text = model.SupplierCode?.ToString();

            SetToolButtonStatus(formStatus);
        }


        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);

            w_Supplier model = new w_Supplier();

            if (string.IsNullOrEmpty(txtID.Text))
            {
                model.ID = int.Parse(txtID.Text);
                model.SupplierName = this.SupplierName.Text;
                model.ContactPerson = this.ContactPerson.Text;
                model.PhoneNumber = this.PhoneNumber.Text;
                model.Email = this.Email.Text;
                model.BeginPay = this.BeginPay.Value;
                model.EndPay = this.EndPay.Value;
                model.TaxtRate = this.TaxtRate.Value;
                model.SortOrder = int.TryParse(this.SortOrder.Text, out var sortOrder) ? sortOrder : 1;
                model.Status = this.Status.Checked;
                model.Remark = this.Remark.Text;
                model.Faxing = this.Faxing.Text;
                model.Address = this.Address.Text;
                model.Bank = this.Bank.Text;
                model.TaxpayerNumber = this.TaxpayerNumber.Text;
                model.BankAccount = this.BankAccount.Text;
                model.LandlinePhone = this.LandlinePhone.Text;
                model.SupplierCode = this.SupplierCode.Text;
                var id = _w_SupplierServices.Insert(model);
                txtID.Text = id.ToString();
            }
            // 修改
            else
            {
                model = _w_SupplierServices.QueryById(int.Parse(txtID.Text));

                model.SupplierName = this.SupplierName.Text;
                model.ContactPerson = this.ContactPerson.Text;
                model.PhoneNumber = this.PhoneNumber.Text;
                model.Email = this.Email.Text;
                model.BeginPay = this.BeginPay.Value;
                model.EndPay = this.EndPay.Value;
                model.TaxtRate = this.TaxtRate.Value;
                model.SortOrder = int.TryParse(this.SortOrder.Text, out var sortOrder) ? sortOrder : 1;
                model.Status = this.Status.Checked;
                model.Remark = this.Remark.Text;
                model.Faxing = this.Faxing.Text;
                model.Address = this.Address.Text;
                model.Bank = this.Bank.Text;
                model.TaxpayerNumber = this.TaxpayerNumber.Text;
                model.BankAccount = this.BankAccount.Text;
                model.LandlinePhone = this.LandlinePhone.Text;
                model.SupplierCode = this.SupplierCode.Text;

                _w_SupplierServices.Update(model);
            }

            if (model.ID > 0)
            {
                MessageBox.Show("保存成功！", "提示");
            }

            SetToolButtonStatus(formStatus);
            RefreshDataGrid();
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _w_SupplierServices.DeleteById(int.Parse(txtID.Text));
                formStatus = FormStatus.Del;
                SetToolButtonStatus(formStatus);
                RefreshDataGrid();
            }
        }

        private void RefreshDataGrid()
        {
            this.dataGridViewList.DataSource = GetData(string.Empty, 1, _pageSize);
        }

        public override void SearchFunction(object sender, EventArgs e)
        {
            base.SearchFunction(sender, e);
            LoadData();
        }

        public override void NextPageFunction(object sender, EventArgs e)
        {
            base.NextPageFunction(sender, e);
            LoadData();
        }

        public override void PrevPageFunction(object sender, EventArgs e)
        {
            base.PrevPageFunction(sender, e);
            LoadData();
        }

        protected override void LoadData()
        {
            string keyword = base.txtSearch.Text.Trim();
            var data = GetData(keyword, _currentPage, _pageSize);
            dataGridViewList.DataSource = data.Items;

            // 更新分页控件
            UpdatePaginationControls(data.TotalCount);
        }

        private IPageList<w_Supplier> GetData(string keyword, int pageIndex, int pageSize)
        {
            Expression<Func<w_Supplier, bool>> predicate = null;

            if (!string.IsNullOrEmpty(keyword))
            {
                predicate = s =>
        s.SupplierName.Contains(keyword) ||
        s.ContactPerson.Contains(keyword) ||
        s.PhoneNumber.Contains(keyword) ||
               false;
            }

            var result = _w_SupplierServices.QueryPage(
                predicate: predicate,
                orderBy: "Id DESC",
                pageIndex: pageIndex,
                pageSize: pageSize
            );

            return result;
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);

        }

        public override bool ValidateData()
        {
            if (string.IsNullOrEmpty(this.SupplierName.Text))
            {
                MessageBox.Show("名称不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(this.ContactPerson.Text))
            {
                MessageBox.Show("联系人不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(this.PhoneNumber.Text))
            {
                MessageBox.Show("手机号码不能为空！");
                return false;
            }
            return true;
        }
    }
}
